package com.apple.reveal.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.apple.reveal.HeaderConstant;
import com.apple.reveal.SessionConstant;

public class LogonInterceptor implements HandlerInterceptor, SessionConstant, HeaderConstant {

	private static final Logger logger = LoggerFactory.getLogger(LogonInterceptor.class);

	private boolean isDevelop;
	private List<String> mobiles;

	public boolean isDevelop() {
		return isDevelop;
	}

	public void setDevelop(boolean isDevelop) {
		this.isDevelop = isDevelop;
	}

	public List<String> getMobiles() {
		return mobiles;
	}

	public void setMobiles(List<String> mobiles) {
		this.mobiles = mobiles;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		/*if (isDevelop) {

			return interceptDev(request, response, handler);
		} else {

			return intercept(request, response, handler);
		}*/
		return true;
	}

	private boolean intercept(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object user = session.getAttribute(SESSION_KEY_USER);
			if (user != null) {
				return true;
			}
		}
		logger.warn("拦截了：" + request.getServletPath());
		response.sendRedirect("./");
		return false;
	}

	private boolean interceptDev(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String mobile = request.getHeader(HEADER_KEY_SESSION_CREATE);
        logger.info(mobile);
		if (mobile == null || !contains(mobile)) {
			return intercept(request, response, handler);
		} else {
			HttpSession session = request.getSession(false);
			if (session != null) {

				Object user = session.getAttribute(SESSION_KEY_USER);
				if (user != null) {
					return true;
				}
			} else {
				session = request.getSession(true);

			}

			session.setAttribute(SESSION_KEY_USER, "张三");
			return true;
		}

	}

	private boolean contains(String mobile) {
		return (this.mobiles != null && this.mobiles.contains(mobile));
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
